import React, { useState, useMemo, useEffect } from 'react';
import { obj_int, obj_str, show_mt, is_empty, ColView, Btn, useHigh, GridTable, filter_row, useCmd, WaitUmd, MainView, BtTxt,
    loc_dt, uDb, no_del, filter_list, InfoDlg, uJob, cline, PanelFind, loc } from 'sui';
import { show_val, load_kind, load_supply, load_col, load_sale } from './cmd';
import { DlgNum, DlgTime } from './ctl';
import { useAccess, User } from 'cache';

const TaskView = () => {
    const [open_info, openInfo] = useState(false);
    const [open_num, openNum] = useState(false);
    const [open_tm, openTm] = useState(false);
    const [col, setCol] = useState();
    const [main, setMain] = useState();
    const [map_supply, mapSupply] = useState();
    const [supply, setSupply] = useState();
    const [map_kind, mapKind] = useState();
    const [high] = useHigh(140, 100);
    const umd = useCmd();
    const [no_acc] = useAccess();

    useEffect(() => {
        load_supply(setSupply, mapSupply);
        load_col(setCol);
        load_kind(null, mapKind);

        load_sale(null, setMain);
    }, []);

    const getRow = useMemo(() => {
        const lst = filter_list(null, col);
        return filter_row(main, lst, umd.filter);
    }, [main, umd.filter, col]);

    const pact = {
        "del": v => {
            if (no_del()) {
                return;
            }

            umd.startWait();

            uDb(null, "buy/rm",
                {
                    line: cline(),
                    k: obj_str(v, "sn"),
                },
                r => load_sale(umd.endWait, setMain),
                e => umd.setErr());
        },
        "order": () => openTm(true),
        "num": () => openNum(true),
        "fin": () => openInfo(true),
    };

    const act = {
        "order": v => {
            umd.startWait();

            uDb(null, "buy/mditem",
                {
                    line: cline(),
                    v: {
                        sn: obj_str(umd.cur, "sn"),
                        state: "run",
                        start: loc_dt(new Date()),
                        pend: loc_dt(new Date(v.pend)),
                        supply: obj_str(v, "supply"),
                        uname: User.uName(),
                    }
                },
                r => load_sale(umd.endWait, setMain),
                e => umd.setErr());
        },
        "num": v =>  {
            umd.startWait();

            uJob(null, "sale/in",
                {
                    line: cline(),
                    v: {
                        sn: obj_str(umd.cur, "sn"),
                        num: obj_int(v, "num"),
                        uname: User.uName(),
                    }
                },
                r => load_sale(umd.endWait, setMain),
                e => umd.setErr());
        },
        "fin": () =>  {
            const sn = obj_str(umd.cur, "sn");
            if (!sn) {
                return;
            }

            umd.startWait();

            uJob(null, "sale/finbuy",
                {
                    line: cline(),
                    k: sn,
                    uname: User.uName(),
                },
                r => load_sale(umd.endWait, setMain),
                e => umd.setErr());
        },
    };


    const getCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const no_open = (d) => d.state !== "open";
        const no_run = (d) => d.state !== "run";

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, frozen: true},
            {name: loc("l_238"), key: 'e_opt', width: 250, frozen: true, formatter: (props) => {
                const d = props.row;
                return (
                    <div className="inline-flex">
                        <BtTxt hcmd={() => umd.pact(pact, d, "del")} disabled={no_acc("wa") || no_open(d)}>{loc("l_237")}</BtTxt>
                        <BtTxt hcmd={() => umd.pact(pact, d, "order")} disabled={no_acc("wa") || no_open(d)}>{loc("l_563")}</BtTxt>
                        <BtTxt hcmd={() => umd.pact(pact, d, "num")} disabled={no_acc("wa") || no_run(d)}>{loc("l_566")}</BtTxt>
                        <BtTxt hcmd={() => umd.pact(pact, d, "fin")} disabled={no_acc("wa")}>{loc("l_526")}</BtTxt>
                    </div>
                );
            }},
        ];

        col.forEach(d => {
            if (d.sn === "kind") {
                tmp.push({name: d.name, key: d.sn, width: 70, formatter: (props) => show_val(props, "kind", map_kind)});
            } else if (d.sn === "supply") {
                tmp.push({name: d.name, key: d.sn, width: 200, formatter: (props) => show_val(props, "supply", map_supply)});
            } else {
                show_mt(tmp, d, 160);
            }
        });

        return tmp;
    };

    const hreturn = () => {
        load_col(setCol);
        umd.hreturn();
    };

    if (umd.isFin("col")) {
        const list = [
            {sn: "buy", name: loc("l_535")},
        ];

        return <ColView hreturn={hreturn} title={loc("l_535")} subtitle={loc("l_221")} list={list} cur="buy"/>;
    }

    const Right = () => (
        <div className="inline-flex">
            <Btn hcmd={() => umd.pact(null, null, "col")} disabled={no_acc("wa")}>{loc("l_221")}</Btn>
        </div>
    );

    const Left = () => (
        <div className="inline-flex items-center">
            {loc("l_535")}
        </div>
    );

    return (
        <MainView>
            <PanelFind left={<Left/>} right={<Right/>} hcmd={v => umd.setFilter(v)}/>
            <GridTable col={getCol()} row={getRow} high={high}/>
            <DlgNum open={open_num} setOpen={openNum} data={umd.cur} hcmd={v => umd.act(act, v)} fin={umd.fin}/>
            <DlgTime open={open_tm} setOpen={openTm} data={umd.cur} hcmd={v => umd.act(act, v)} supply={supply} map_supply={map_supply}/>
            <InfoDlg open={open_info} setOpen={openInfo} msg={loc("l_764")} hcmd={() => umd.act(act)} hcancel={() => openInfo(false)}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {TaskView};
